package za.org.jcicada.datastore.impl.mongodb;

import java.net.URI;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public final class MongoDB {

	private static Map<URI, MongoDB> instances = new HashMap<URI, MongoDB>();
	
	private DB database;
	
	private MongoDB(URI connectionURI) throws UnknownHostException, MongoException {
		Mongo mongo;
		String[] path = connectionURI.getPath().split("/");
		if (connectionURI.getHost() == null)
			mongo = new Mongo();
		else if (connectionURI.getPort() == -1)
			mongo = new Mongo(connectionURI.getHost());
		else
			mongo = new Mongo(connectionURI.getHost(), connectionURI.getPort());
		database = mongo.getDB(path[1]);
	}
	
	public synchronized static MongoDB getInstance(URI connectionURI) throws UnknownHostException, MongoException {
		if (!instances.containsKey(connectionURI)) {
			instances.put(connectionURI, new MongoDB(connectionURI));
		}
		return instances.get(connectionURI);
	}
	
	public DB getDB() {
		return database;
	}
}
